#include "./protocol.h"
#include <NewSoftSerial.h>

protocol Master;

/*oggetto New Soft Serial v11*/
NewSoftSerial nss(8,9);  //RX:8 TX:9 nss debug

/*variabili per temporizzazione in main loop*/
unsigned long int now=0;
unsigned long int beforeIntTemp=0;
unsigned long int beforeIntTempSending=0;

float sensorReading=0.0;
float vref=1.084; 			//voltage internal used to reference
int fahrenheit=0;
int centigrade=0;


/********************************************************************
/* Setup
/********************************************************************/
void setup(){
	Master.start(9600);
	nss.begin(9600);
	
	analogReference(INTERNAL);			//internal reference approximatly 1.1V
	delay(10);
	pinMode(LAMP1pin,OUTPUT);
	pinMode(LAMP2pin,OUTPUT);
	pinMode(LOAD1pin,OUTPUT);
	
	digitalWrite(LAMP1pin, LOW);
	digitalWrite(LAMP2pin, LOW);
	digitalWrite(LOAD1pin, LOW);
	
	pinMode(8, INPUT);
	pinMode(9, OUTPUT);
	
	now=millis();
	beforeIntTemp=millis();
	beforeIntTempSending=millis();
}


/********************************************************************
/* Main Loop
/********************************************************************/
void loop(){
	now=millis();
	
	if(now>(beforeIntTemp+10000)){								//ogni 10 secondi
		//aggiornamento var stato ext temp
		sensorReading = analogRead(A0);        					// analog reading from the LM34 (0 - 1023) 
		fahrenheit = (100.0 * sensorReading * vref)/1023;   	// calculates fahrenheit temperature
		centigrade = (((5.0/9.0))*(fahrenheit-32.0)); 			//conversion to degrees C		
		Master.setTemp(centigrade);
		beforeIntTemp=millis();
	}
	if(now>(beforeIntTempSending+30000)){						//ogni 30 secondi
		Master.sendInternalTemp();
		beforeIntTempSending=millis();		
	}	
	
	if(Serial.available()>0){
		Master.readMessage((char)Serial.read());
		//Serial.println((char)Serial.read());
	}	
}
